﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Inovout.Gis
{
    public abstract class MapObject
    {
        private static readonly IDictionary<Type, MapObject> mapDictionaries = new Dictionary<Type, MapObject>();

        public static T GetMap<T>() where T : MapObject
        {
            MapObject map;
            if (!mapDictionaries.TryGetValue(typeof(T), out map))
            {
                map = Activator.CreateInstance<T>();
                Configuration config = SessionFactoryHolder.Instance.GetConfiguration(typeof(T));
                map.Build(config);
                mapDictionaries.Add(typeof(T), map);
            }
            return map as T;
        }
        public abstract void Build(Configuration config);

        public static IMapInfo Current;

        private List<GeometryLayerObject> layers;

        public GeometryLayerObject[] Layers
        {
            get
            {
                if (layers == null)
                {
                    layers = new List<GeometryLayerObject>();
                    IGisSessionFactory sessionFactory = SessionFactoryHolder.Instance.GetSessionFactory(this.GetType());
                    IGisSession session = sessionFactory.OpenSession();
                    layers.AddRange(session.GetGeometryLayers(this.GetType()).Cast<GeometryLayerObject>());
                }
                return layers.ToArray();
            }
        }

        private void OpenSession()
        {
            throw new NotImplementedException();
        }

        //private void Build()
        //{
        //    IEnumerable<GeometryLayerObject> layerObjects = BuildFromGis();
        //    if (layerObjects == null)
        //    {
        //        layerObjects = BuildFromRepositroy();
        //    }
        //    if (layerObjects == null)
        //    {
        //        layers = new List<GeometryLayerObject>();
        //    }
        //    else
        //    {
        //        layers.AddRange(layerObjects);
        //    }
        //}
        //protected virtual IEnumerable<GeometryLayerObject> BuildFromGis()
        //{
        //    return null;
        //}
        //protected string[] layerNames;
        //protected virtual IEnumerable<GeometryLayerObject> BuildFromRepositroy()
        //{
        //    List<GeometryLayerObject> layerObjects = new List<GeometryLayerObject>();
        //    IGisSession session = sessionFactoryHolder.CreateSession();
        //    foreach (string layerName in layerNames)
        //    {
        //        layerObjects.Add(session.BuildLayer(layerName) as GeometryLayerObject);
        //    }
        //    return layerObjects;

        //}
    }
}
